import {
  TextField,
  IndexTable,
  LegacyCard,
  IndexFilters,
  useSetIndexFiltersMode,
  useIndexResourceState,
  ChoiceList,
  RangeSlider,
  Badge,
  LegacyStack,
  RadioButton,
  Link,
  Pagination,
  Button,
} from "@shopify/polaris";
import type { IndexFiltersProps, TabProps } from "@shopify/polaris";
import { useState, useCallback } from "react";

import styled from "./Tables.module.less";
interface Props {
  tableData: ORDERMODULE.Items[];
}
function IndexTableWithLoadingExample(props: Props) {
  const [pagenumber, setPagenumber] = useState(1);

  const [values, setValues] = useState("1");

  const handleChanges = useCallback(
    (newValue: string) => setValues(newValue),
    []
  );

  const sleep = (ms: number) =>
    new Promise((resolve) => setTimeout(resolve, ms));
  const [itemStrings, setItemStrings] = useState([
    "全部",
    "未发货",
    "未付款",
    "打开",
    "已关闭",
  ]);
  const deleteView = (index: number) => {
    const newItemStrings = [...itemStrings];
    newItemStrings.splice(index, 1);
    setItemStrings(newItemStrings);
    setSelected(0);
  };

  const duplicateView = async (name: string) => {
    setItemStrings([...itemStrings, name]);
    setSelected(itemStrings.length);
    await sleep(1);
    return true;
  };

  const tabs: TabProps[] = itemStrings.map((item, index) => ({
    content: item,
    index,
    onAction: () => {},
    id: `${item}-${index}`,
    // isLocked: index === 0,
    actions:
      index === 0
        ? [
            {
              // type: "rename",
              type: "edit-columns",
              onAction: () => {},
              onPrimaryAction: async (value: string): Promise<boolean> => {
                const newItemsStrings = tabs.map((item, idx) => {
                  if (idx === index) {
                    return value;
                  }
                  return item.content;
                });
                await sleep(1);
                setItemStrings(newItemsStrings);
                return true;
              },
            },
          ]
        : //  控制all 有无icon dwon  数据过滤
          [
            {
              // type: "rename",
              type: "rename",
              onAction: () => {},
              onPrimaryAction: async (value: string): Promise<boolean> => {
                const newItemsStrings = tabs.map((item, idx) => {
                  if (idx === index) {
                    return value;
                  }
                  return item.content;
                });
                await sleep(1);
                setItemStrings(newItemsStrings);
                return true;
              },
            },
            {
              type: "duplicate",
              onPrimaryAction: async (value: string): Promise<boolean> => {
                await sleep(1);
                duplicateView(value);
                return true;
              },
            },
            {
              type: "edit",
            },
            {
              type: "delete",
              onPrimaryAction: async () => {
                await sleep(1);
                deleteView(index);
                return true;
              },
            },
          ],
  }));
  const [selected, setSelected] = useState(0);
  const onCreateNewView = async (value: string) => {
    await sleep(500);
    setItemStrings([...itemStrings, value]);
    setSelected(itemStrings.length);
    return true;
  };
  const sortOptions: IndexFiltersProps["sortOptions"] = [
    { label: "订单", value: "order asc", directionLabel: "升序" },
    { label: "订单", value: "order desc", directionLabel: "降序" },
    { label: "日期", value: "date asc", directionLabel: "由新到旧" },
    { label: "日期", value: "date desc", directionLabel: "由旧到新" },
    { label: "Customer", value: "customer asc", directionLabel: "A-Z" },
    { label: "Customer", value: "customer desc", directionLabel: "Z-A" },
    { label: "总计", value: "total asc", directionLabel: "高到低" },
    { label: "总计", value: "total desc", directionLabel: "低到高" },
    { label: "支付状态", value: "paymoney asc", directionLabel: "A-Z" },
    { label: "支付状态", value: "paymoney desc", directionLabel: "Z-A" },
    { label: "实现状态", value: "state asc", directionLabel: "A-Z" },
    { label: "实现状态", value: "state desc", directionLabel: "Z-A" },
  ];
  const [sortSelected, setSortSelected] = useState(["order asc"]);
  const { mode, setMode } = useSetIndexFiltersMode();
  const onHandleCancel = () => {};

  const onHandleSave = async () => {
    await sleep(1);
    return true;
  };

  const primaryAction: IndexFiltersProps["primaryAction"] =
    selected === 0
      ? {
          type: "save-as",
          onAction: onCreateNewView,
          disabled: false,
          loading: false,
        }
      : {
          type: "save",
          onAction: onHandleSave,
          disabled: false,
          loading: false,
        };
  const [accountStatus, setAccountStatus] = useState<string[] | undefined>(
    undefined
  );
  const [moneySpent, setMoneySpent] = useState<[number, number] | undefined>(
    undefined
  );
  const [moneystates, setMoneystates] = useState<string | undefined>(undefined);
  const [taggedWith, setTaggedWith] = useState<string>("");
  const [queryValue, setQueryValue] = useState<string>("");

  const handleAccountStatusChange = useCallback(
    (value: string[]) => setAccountStatus(value),
    []
  );
  //分割
  const [value, setValue] = useState("付款状态");

  const handleChange = useCallback((_: boolean, newValue: string) => {
    setValue(newValue);
    setMoneystates(newValue);
  }, []);

  //分割

  const handleMoneySpentChange = useCallback(
    (value: [number, number]) => setMoneySpent(value),
    []
  );
  const handleTaggedWithChange = useCallback(
    (value: string) => setTaggedWith(value),
    []
  );
  const handleFiltersQueryChange = useCallback(
    (value: string) => setQueryValue(value),
    []
  );
  const handleAccountStatusRemove = useCallback(
    () => setAccountStatus(undefined),
    []
  );
  const handleMoneySpentRemove = useCallback(
    () => setMoneySpent(undefined),
    []
  );
  const handleTaggedWithRemove = useCallback(() => setTaggedWith(""), []);
  const handleQueryValueRemove = useCallback(() => setQueryValue(""), []);
  const handleMoneyStatesRemove = useCallback(() => setMoneystates(""), []);
  const handleFiltersClearAll = useCallback(() => {
    handleAccountStatusRemove();
    handleMoneySpentRemove();
    handleTaggedWithRemove();
    handleQueryValueRemove();
    handleMoneyStatesRemove();
  }, [
    handleAccountStatusRemove,
    handleMoneySpentRemove,
    handleQueryValueRemove,
    handleTaggedWithRemove,
    handleMoneyStatesRemove,
  ]);

  //add filter
  const filters = [
    {
      key: "accountStatus",
      label: "配送方式",
      filter: (
        <ChoiceList
          title="配送方式"
          titleHidden
          choices={[
            { label: "本地配送", value: "本地配送" },
            { label: "到店取货", value: "到店取货" },
            { label: "为客户发货", value: "为客户发货" },
          ]}
          selected={accountStatus || []}
          onChange={handleAccountStatusChange}
          allowMultiple
        />
      ),
      shortcut: true,
    },
    {
      key: "taggedWith",
      label: "目的地",
      filter: (
        <TextField
          label="Tagged with"
          value={"666"}
          onChange={handleTaggedWithChange}
          autoComplete="off"
          labelHidden
        />
      ),
      shortcut: true,
    },
    {
      key: "moneySpent",
      label: "状态",
      shortcut: true,
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "moneystates",
      label: "付款状态",
      shortcut: true,
      filter: (
        <LegacyStack vertical>
          <RadioButton
            label="未付"
            checked={value === "未付"}
            id="未付"
            name="未付"
            onChange={handleChange}
            value={moneystates}
          />
          <RadioButton
            label="已付"
            id="已付"
            name="已付"
            checked={value === "已付"}
            onChange={handleChange}
            value={moneystates}
          />
        </LegacyStack>
      ),
    },
    {
      key: "product",
      label: "产品",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "fastates",
      label: "发货状态",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "songstate",
      label: "配送状态",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "tuihuostates",
      label: "退货状态",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "biaoqian",
      label: "具有以下标签",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "unbiaoqian",
      label: "不具有标签",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "app",
      label: "应用",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "unpaidstates",
      label: "拒付和质询状态",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
    {
      key: "le",
      label: "风险等级",
      filter: (
        <LegacyStack vertical>
          <RadioButton
            label="Accounts are disabled"
            helpText="Customers will only be able to check out as guests."
            checked={value === "disabled"}
            id="disabled"
            name="accounts"
            onChange={handleChange}
          />
          <RadioButton
            label="Accounts are optional"
            helpText="Customers will be able to check out with a customer account or as a guest."
            id="optional"
            name="accounts"
            checked={value === "optional"}
            onChange={handleChange}
          />
        </LegacyStack>
      ),
    },
  ];

  //  数据处理
  const appliedFilters: IndexFiltersProps["appliedFilters"] = [];
  if (accountStatus && !isEmpty(accountStatus)) {
    const key = "accountStatus";
    appliedFilters.push({
      key,
      label: disambiguateLabel(key, accountStatus),
      onRemove: handleAccountStatusRemove,
    });
  }
  if (moneySpent) {
    const key = "moneySpent";
    appliedFilters.push({
      key,
      label: disambiguateLabel(key, moneySpent),
      onRemove: handleMoneySpentRemove,
    });
  }
  if (!isEmpty(taggedWith)) {
    const key = "taggedWith";
    appliedFilters.push({
      key,
      label: disambiguateLabel(key, taggedWith),
      onRemove: handleTaggedWithRemove,
    });
  }
  if (moneystates) {
    const key = "moneystates";
    appliedFilters.push({
      key,
      label: disambiguateLabel(key, moneystates),
      onRemove: handleMoneyStatesRemove, //此方法 可以调用自身方法 清除 本标签
    });
  }

  const orders = props.tableData.map((item, index) => {
    return { ...item, id: String(index) };
  });

  const resourceName = {
    singular: "order",
    plural: "orders",
  };

  const { selectedResources, allResourcesSelected, handleSelectionChange } =
    useIndexResourceState(orders);

  const rowMarkup = orders.map(
    (
      {
        id,
        order_no,
        create_time,
        consignee,
        delivery_status,
        payment_status,
        get_order_product,
        get_delivery,
        email,
        pay_amount,
      },
      index
    ) => (
      <IndexTable.Row
        id={id}
        key={id}
        selected={selectedResources.includes(id)}
        position={index}
        // subdued //字体色 灰
      >
        <IndexTable.Cell>
          <Link
            url={"order/" + order_no}
            dataPrimaryLink
            onClick={() => {
              localStorage.setItem("xiangqing", order_no);
            }}
          ></Link>
          <div style={{ fontSize: "13px" }}>{"#" + order_no}</div>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <div>
            <div style={{ fontSize: "12px" }}>
              {String(create_time).slice(0, 4) +
                "年" +
                String(create_time).slice(5, 7) +
                "月" +
                String(create_time).slice(8, 10) +
                "日"}
            </div>
          </div>
        </IndexTable.Cell>
        <IndexTable.Cell>
          {/* <div style={{ fontSize: "13px" }} className={styled.T2}>
            <div>{consignee}</div>
            <div style={{ fontSize: "12px", color: "rgb(109 , 113, 117)" }}>
              {email}
            </div>
          </div> */}
          <div style={{ fontSize: "13px" }}>{consignee}</div>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <div style={{ fontSize: "13px" }}>{"￥" + pay_amount}</div>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <span>
            {
              [
                <Badge progress="partiallyComplete">未发货</Badge>,
                <Badge status="success" progress="complete">
                  已发货
                </Badge>,
              ][delivery_status]
            }
          </span>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <span>
            {
              [
                <Badge progress="partiallyComplete">未付款</Badge>,
                <Badge status="success" progress="complete">
                  已付款
                </Badge>,
              ][payment_status]
            }
          </span>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <div style={{ fontSize: "14px", marginLeft: "13%" }}>
            {get_order_product[0].quantity}件商品
          </div>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <div></div>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <div></div>
        </IndexTable.Cell>
        <IndexTable.Cell>
          <div></div>
        </IndexTable.Cell>
      </IndexTable.Row>
    )
  );

  const promotedBulkActions = [
    {
      content: "标为已发货",
      onAction: () => console.log("Todo: implement create shipping labels"),
    },
    {
      content: "入账付款",
      onAction: () => console.log("Todo: implement mark as fulfilled"),
    },
    {
      content: "Capture payment",
      onAction: () => console.log("Todo: implement capture payment"),
    },
  ];
  const bulkActions = [
    {
      content: "请求发货",
      onAction: () => console.log("Todo: implement bulk add tags"),
    },
    {
      content: "移除状态",
      onAction: () => console.log("Todo: implement bulk remove tags"),
      disabled: true,
    },
    {
      content: "Delete customers",
      onAction: () => console.log("Todo: implement bulk delete"),
      url: "http://baidu.com",
    },
    {
      content: "Delete customers",
      onAction: () => console.log("Todo: implement bulk delete"),
    },
    {
      content: "Delete customers",
      onAction: () => console.log("Todo: implement bulk delete"),
    },
    {
      content: "Delete customers",
      onAction: () => console.log("Todo: implement bulk delete"),
    },
    {
      content: "取消订单",
      onAction: () => console.log("Todo: implement bulk delete"),
    },
    {
      content: "添加标记",
      onAction: () => console.log("Todo: implement bulk delete"),
    },
    {
      content: "删除标记",
      onAction: () => console.log("Todo: implement bulk delete"),
    },
  ];

  return (
    <LegacyCard>
      {/* <div className={styled.box}> */}
      <IndexFilters
        sortOptions={sortOptions} //排序按钮
        sortSelected={sortSelected}
        queryValue={queryValue} //搜索
        queryPlaceholder="搜索所有 订单"
        onQueryChange={handleFiltersQueryChange}
        onQueryClear={() => {}}
        onSort={setSortSelected}
        primaryAction={primaryAction}
        cancelAction={{
          onAction: onHandleCancel,
          disabled: false,
          loading: false,
        }}
        tabs={tabs}
        selected={selected}
        onSelect={setSelected}
        canCreateNewView
        onCreateNewView={onCreateNewView}
        filters={filters}
        appliedFilters={appliedFilters}
        onClearAll={handleFiltersClearAll}
        mode={mode}
        setMode={setMode}
        // loading
      />

      <IndexTable
        bulkActions={bulkActions}
        promotedBulkActions={promotedBulkActions}
        resourceName={resourceName}
        // resourceName={rows}
        // selectable

        //排序
        sortable={[true, true, true, true, true, true, true, true, true, true]}
        //排序
        itemCount={orders.length}
        selectedItemsCount={
          allResourcesSelected ? "All" : selectedResources.length
        }
        onSelectionChange={handleSelectionChange}
        headings={[
          { title: "订单" },
          { title: "日期" },
          { title: "客户" },
          { title: "总计" },
          { title: "发货状态" }, // alignment: "end"  对齐方式
          { title: "付款状态" },
          { title: "商品" },
          { title: "配送状态" },
          { title: "配送方式" },
          { title: "标签" },
        ]}
      >
        {rowMarkup}
      </IndexTable>
      <div className={styled.pages}>
        <LegacyCard.Section>
          <div className={styled.children}>
            <div>共 {10} 条</div>
            <div className={styled.middle}>
              <Button>{String(10)}条/页</Button>
            </div>
            <div>
              <Pagination
                label={pagenumber}
                hasPrevious
                onPrevious={() => {
                  console.log("上一页");
                  setPagenumber(pagenumber - 1);
                }}
                hasNext
                onNext={() => {
                  console.log("下一页");
                  setPagenumber(pagenumber + 1);
                }}
              />
            </div>
            <div className={styled.pageright}>
              <div>前往</div>
              <div className={styled.Text}>
                <TextField
                  label=""
                  value={values}
                  onChange={handleChanges}
                  autoComplete="off"
                />
              </div>
              <div>页</div>
            </div>
          </div>
        </LegacyCard.Section>
      </div>
      {/* </div> */}
    </LegacyCard>
  );

  function disambiguateLabel(key: string, value: string | any[]): string {
    switch (key) {
      case "moneySpent":
        return `Money spent is between $${value[0]} and $${value[1]}`;
      case "taggedWith":
        return `Tagged with ${value}`;
      case "accountStatus":
        // return (value as string[]).map((val) => `Customer ${val}`).join(", ");//Customer
        return (value as string[]).map((val) => ` ${val}`).join(", ");
      default:
        return value as string;
    }
  }

  function isEmpty(value: string | string[]): boolean {
    if (Array.isArray(value)) {
      return value.length === 0;
    } else {
      return value === "" || value == null;
    }
  }
}

export default IndexTableWithLoadingExample;
